﻿using huqiang.Core.HGUI;
using huqiang.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;

namespace huqiang.UIModel
{
    public class SceneUIBase:MonoBehaviour
    {
        public TextAsset asset;
        [SerializeField]
        [HideInInspector]
        public byte[] LayoutData;
        DataBuffer db;
        FakeStruct[] tables;
        FakeStruct models;
        
        unsafe void LoadModels(DataBuffer db)
        {
            var fake = db.fakeStruct;
            models = fake.GetData<FakeStruct>(0);
            Int16[] arr = fake.GetData<Int16[]>(1);
            if (arr != null)
            {
                FakeStruct[] fsa = new FakeStruct[arr.Length];
                for (int i = 0; i < arr.Length; i++)
                    fsa[i] = db.GetData(arr[i]) as FakeStruct;
                tables = fsa;
            }
        }
        public void Awake()
        {
            if(asset!=null)
            {
                db = new DataBuffer(asset.bytes);
                LoadModels(db);
            }else if(LayoutData!=null)
            {
                db = new DataBuffer(LayoutData);
                LoadModels(db);
            }
            Initial();
        }
        public T LoadUI<T>(UIElement Parent, string name) where T : class, new()
        {
            if (models == null)
                return null;
            if (Parent == null)
                Parent = GetComponent<HGUIRender>().canvas;
            var model = HGUIManager.FindChild(models,name);
            T t = new T();
            var uiInitializer = new UIInitializer(UIBase.ObjectFields(typeof(T)));
            uiInitializer.Reset(t);
            var Main = HGUIManager.Clone(model, uiInitializer);
            uiInitializer.Done();
            Main.SetParent(Parent);
            Main.localPosition = Vector3.zero;
            Main.localScale = Vector3.one;
            Main.localRotation = Quaternion.identity;
            Main.activeSelf = true;
            return t;
        }
        public virtual void Initial()
        {

        }
    }
}
